package com.project.service.impl;

import com.project.bean.CutPageBean;
import com.project.bean.ProductBean;
import com.project.mapper.IProductMapper;
import com.project.service.IProductService;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDate;
import java.util.List;

public class ProductServiceImpl extends BaseService implements IProductService {
    @Override
    public void add(ProductBean productBean) {

        SqlSession session = this.getSession();
        IProductMapper mapper = session.getMapper(IProductMapper.class);
        mapper.add(productBean);

        session.commit();
        session.close();
    }

    @Override
    public void del(int id) {

        SqlSession session = this.getSession();
        IProductMapper mapper = session.getMapper(IProductMapper.class);
        mapper.del(id);

        session.commit();
        session.close();
    }

    @Override
    public void update(int id, int price) {

        SqlSession session = this.getSession();
        IProductMapper mapper = session.getMapper(IProductMapper.class);
        mapper.update(id,price);

        session.commit();
        session.close();
    }

    @Override
    public ProductBean findById(int id) {
        SqlSession session = this.getSession();
        IProductMapper mapper = session.getMapper(IProductMapper.class);
        ProductBean productBean = mapper.findById(id);

        session.close();
        return productBean;
    }

    @Override
    public CutPageBean<ProductBean> cutByNamePrice(int pageNo,
       String name, int minPrice, int maxPrice) {

        CutPageBean<ProductBean> cutPageBean = new CutPageBean<>();
        SqlSession session = this.getSession();
        IProductMapper mapper = session.getMapper(IProductMapper.class);

        List<ProductBean> list = mapper.cutByNamePrice(
                (pageNo-1)*CutPageBean.PAGESIZE,
                CutPageBean.PAGESIZE, name,minPrice,maxPrice
        );
        cutPageBean.setList(list);

        int count = mapper.countByName(name,minPrice,maxPrice);

        cutPageBean.setCount(count);
        session.close();

        return cutPageBean;
    }

    @Override
    public CutPageBean<ProductBean> cutByItem(int pageNo,
          String factory, LocalDate startDate, LocalDate endDate) {

            CutPageBean<ProductBean> cutPageBean = new CutPageBean<>();
            SqlSession session = this.getSession();
            IProductMapper mapper = session.getMapper(IProductMapper.class);

            List<ProductBean> list = mapper.cutByItem(
                    (pageNo-1)*CutPageBean.PAGESIZE,
                    CutPageBean.PAGESIZE, factory,startDate,endDate
            );
            cutPageBean.setList(list);
            int count = mapper.countItem(factory,startDate,endDate);

            cutPageBean.setCount(count);
            session.close();

            return cutPageBean;
    }
}
